package cn.edu.servlet;

import cn.edu.entity.User;
import cn.edu.service.UserService;

import cn.edu.service.UserServiceImpl;
import cn.edu.util.URIUtil;
import cn.edu.util.UserUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

//@WebServlet("*.user")
public class UserServlet extends HttpServlet {
    UserService service;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        System.out.println(req.getRequestURI());
        String path = URIUtil.subUri(req.getRequestURI());

        if("login".equals(path)){
            //执行登陆代码
            //1.从页面获取用户输入的内容.
            String nameStr = req.getParameter("u_name");
            String pwdStr = req.getParameter("u_password");
            //2.从数据获取所有的用户.
            //3.比较用户输入的与数据库的数据是否能匹配上,
//                2.1设计Dao层的一个方法. 将用户名放到数据库进行查找
                    //3.1,如果能匹配上,那么代表登陆成功,转发到登陆成功页面
                    //3.2,如果匹配不上,则说明没有当前用户,重定向到登陆失败页面.
            service = new UserServiceImpl();
            boolean boo = service.exites(nameStr);
            //如果存在,再去检验密码是否匹配
            User user = new User();
            user.setName(nameStr);
            user.setPassword(pwdStr);
            if(service.isLogon(user)){
                req.setAttribute("msg","登陆成功");
                req.setAttribute("name",nameStr);
                req.getRequestDispatcher("/front/success.jsp").forward(req,resp);
            }else{
               resp.sendRedirect("/front/fail.jsp");
            }
        }else if("reg".equals(path)){
            //执行注册代码
            System.out.println("执行注册代码");
            User user = new User();
            user.setName(req.getParameter("u_name"));
            user.setPassword(req.getParameter("u_pwd"));
            //通过对象的调用,直接返回对应的业务逻辑的结果.
//            service = new UserServiceImpl();
//            boolean boo = service.insertUser(user);
//            if(boo){
//                req.setAttribute("msg","您好,"+user.getName()+",欢迎登陆");
//                req.getRequestDispatcher("/front/index.jsp").forward(req,resp);
//            }else{
//                req.setAttribute("msg","当前用户数据错误,请重新输入");
//                req.getRequestDispatcher("WEB-INF/error.jsp").forward(req,resp);
//            }
        }
    }
}
